package com.wlz.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;

/**
 * @author wlz
 * @date 2022-07-06  11:49 下午
 */
@Slf4j
public class MyNettyClient {

    public static void main(String[] args) {

        EventLoopGroup group = new NioEventLoopGroup();

        try {
            // 创建客户端启动对象
            // 注意客户端使用的是 Bootstrap ，而不是 ServerBootstrap
            Bootstrap bootstrap = new Bootstrap();

            // 设置相关参数
            bootstrap.group(group) // 设置线程组
                    .channel(NioSocketChannel.class) // 使用 NioSocketChannel 作为客户端的通道实现
                    .handler(new ChannelInitializer<SocketChannel>() {

                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            // 加入 处理器
                            socketChannel.pipeline().addLast(new MyNettyClientHandler());
                        }
                    });

            log.info(" netty client start ....");

            // 启动客户端去连接服务器端
            ChannelFuture channelFuture = bootstrap.connect("localhost", 9000).sync();

            // 对关闭 通道进行 监听
            channelFuture.channel().closeFuture().sync();

        } catch (Exception e) {
            log.info("error : {}", e);
        }finally {
            group.shutdownGracefully();
        }
    }
}
